//Ext.nameSpace("App");
Ext.namespace("Pub");
Ext.namespace("Run");
Ext.namespace("Init");
Pub.gridPageSize = 25;
Pub = {
	init:function(){return this.json.init(this);},
	log:function(p){console.log(p);},
	unique:function(){return this.string.unique();},
	//random:Math.random(),
	arrayUnique:function(arr){ return this.array.unique(arr);},
	array:{
		formatBytpl:function(p,tpl){
			var toExe = arguments[2] || false;
			for (var i = 0; i < p.length; i++) {
				if(toExe){
					eval('r[i] = '+tpl.replace(/\{$v\}/g,p[i]));
				}else{
					r[i] = tpl.replace(/\{$v\}/g,p[i]);
				}
			};
			return r;
		},
		unique:function(arr){
			var n = {},r=[];
			for(var i = 0; i < arr.length; i++){
				if (!n[arr[i]]){
					n[arr[i]] = true;
					r.push(arr[i]);
				}
			}
			delete n;
			return r;
		}
	},
	extVersion:function(){
		if(!(this.__extVersion || false)) this.__extVersion = ((Ext.getVersion('extjs')||'3.4') +'').substr(0,3);
		return this.__extVersion;
	},
	layout:function(p){
		return this.__extVersion>3.9 ? {"type":p} :p;
	},
	clsToFile:function(cls){
		var jsPath = (Init.path.tplPublic || '')+'Js/';
		var isString = false;
		if(typeof(cls)==='string'){
			cls = [cls];
			isString = true;
		}
		for(var k in cls){
			if(typeof(cls[k])==='string'){
				cls[k] = (cls[k]+'').replace('App.','@@@@').replace('Run.','@@@@').replace('.','_').toLowerCase().replace('@@@@',jsPath).replace('@@@@','');
				cls[k] += '.js';
			}
		}
		if(isString) return cls[0];
		return cls;
	},
	
	cls:{
		define:function(str,cfg){		
			var ext = cfg.extend || 'Ext.Panel'; delete cfg.extend;
			//alert(uneval(cfg));
			var tmp = str.split('.');
			
			if(tmp.length>1){
				delete tmp[tmp.length-1];
				var ns = tmp.join('.');
				var ns = tmp.join('.').replace(/\.+\s*$/,'');
				try{
					typeof(eval(ns));
				}catch(exception){
					Ext.namespace(ns);
				}
			}
			cfg.callInit = function(p){var me=this;eval(str+'.superclass.initComponent.call(me,p||{});');};
			//alert(str+'=Ext.extend('+ext+',cfg);');
			cfg.initComponent = cfg.initComponent || function(){/*cfg.callInit(this);*/};
			if( (typeof(eval(ext)) || 'undefined')=='undefined' ){
				this.loadCls(ext, function(){eval(str+'=Ext.extend('+ext+',cfg);');});
			}else eval(str+'=Ext.extend('+ext+',cfg);' );
			return;
		},
		create:function(cls,cfg){
			var hasCls;
			eval(hasCls = cls+'||false');
			if(hasCls){
				
			}
		}
	},
	
	define:function(str,cfg){		
		this.cls.define(str,cfg);
	},
	
	create:function( cls,cfg,fn ){
		function tmpFn(){
			eval('var cmp = new '+cls+'(cfg)');
			if(fn || false){
				fn(cmp);
			}else return cmp;
		}

		var tmp = cls.split('.');
		if(tmp.length>1){
			delete tmp[tmp.length-1];
			var ns = tmp.join('.').replace(/\.+\s*$/,'');
			try{
				typeof(eval(ns));
			}catch(exception){
				Ext.namespace(ns);
			}
		}

		if( (typeof(eval(cls)) || 'undefined')=='undefined' ){
			Pub.loadCls(cls,tmpFn);
		}else return new tmpFn();
	},

	apply:function(cls,cfg){
		var __loaded = false;
		var __result = false;
		if(!typeof(cls)){
			Ext.Loader.load([this.clsToFile(cls)],function(){
			 	eval('__result= new '+cls+'(cfg)');
			 	__loaded = true;
			});
			while(!__loaded){}
		}else{
			eval('__result= new '+cls+'(cfg)');
		}
		return __result;
	},
	
	relyRun: function(callback,cls)
	{   
		var timeinterval = arguments[2] || 500;
		var maxTimes = arguments[3] || 10;
		var nowTimes = arguments[4] || 0;
		tmp(callback,cls,timeinterval,maxTimes,nowTimes);
		
		function tmp(fn,cls,tt,max,now){
			now++;
			if(now>max)return false;
			var result = false;
			for(var k in cls){
				if(typeof(cls[k])==='string' && (typeof(eval(cls[k])) || 'undefined')=='undefined' ){
					result = true;
					break;
				}
			}
			if( result ){
				setTimeout(function(){tmp(fn,cls,tt,max,now);},tt);
			}else{
				if(typeof(fn)==='string')eval(fn);
				else fn();
		    }
		}		
	},
	
	url:function(str){
		var appUrl= arguments[1] || '';
		var arr=str.split('\?');
		if(arr.length>1) {arr[1] = '&'+arr[1];}
		else {arr[1] = '';}		
		var _arr=arr[0].split('/');
		return appUrl+'?m='+_arr[0]+'&a='+_arr[1]+arr[1];
	},
	ico:function(str){
		return 'Tpl/default/Public/Image/icon-'+str+'.png';
	},
	src:function(str){
		str = str.replace('---','Tpl/default/Public/');
		str = str.replace('[PUBLIC]',(Init.path.public||''));
		str = str.replace('[JSFW]',(Init.path.JSFW||''));
		return str;
	},
	img:function(str){
		var w = (arguments[1]||false) ? ' width="'+arguments[1]+'px" ' : '';
		var h = (arguments[2]||false) ? ' height="'+arguments[2]+'px" ' : ''; //可选 参数
		var other = arguments[3] || ''; //可选 参数
		str = str==''? Pub.ico('separator'): str;
		return '<img src="'+(str.replace('---','Tpl/default/Public/'))+'"'+w+h+other+'/>';
	},
	http:{
		request:function(cfg){
			var fn = arguments[2] || false;
			var maskCmp = false;
			if(cfg.maskCmp){
				maskCmp = typeof(cfg.maskCmp)==='string'? Ext.getCmp(cfg.maskCmp): cfg.maskCmp;
			}
			if(maskCmp)maskCmp.setDisabled(true);
			var cfg = Ext.apply({
				method:'GET',
				params:arguments[1] || {},
				success:function (response, opts){
					if(maskCmp)maskCmp.setDisabled(false);
					obj = Ext.util.JSON.decode(response.responseText);
					if(obj.NoAuth || false){alert('权限不足');}
					if(obj.LoginOverTime || false){location.href=location.href;}

					if(fn) fn(obj);
					
				},
			    failure: function(response, opts){
			        //console.log('server-side failure with status code ' + response.status);
			        if(maskCmp)maskCmp.setDisabled(false);
			    }
			},cfg);
			Ext.Ajax.request(cfg);
		},
		get:function(url){
			var fun = arguments[2] || false;
			var cfg = Ext.apply({
				method:'GET',
				url:url,
				params:arguments[1] || {}
				//maskCmp:arguments[1] || false,
			},  (arguments[3]||{}) );
			this.request(cfg, (arguments[1]||{}), fun);	
		},
		post:function(url){
			var fun = arguments[2] || false;
			var cfg = Ext.apply({
					method:'POST',
					params:arguments[1] || {},
					url:url
					//maskCmp:arguments[1] || false,
			},  (arguments[3]||{}) );
			this.request(cfg, (arguments[1]||{}), fun);		
		}//,
		/*loadCls:function(){
			
		}*/
	},
	post:function(){
		var me = this;
		this.http.post(
			(arguments[1] || ''),
			(arguments[0] || ''),
			(arguments[2] || ''),
			(arguments[3] || '')
		);
	},
	disable:function(cmp,status){
		var overTime = arguments[2] || 0;
		var cmp = typeof(cmp)==='string'? Ext.getCmp(cmp): cmp;
		cmp.setDisabled(status);
		if(status && overTime>0){
			setTimeout(function(){cmp.setDisabled(false);},overTime);
		}
	},
	wait:function(){
		var overTime = arguments[1] || 3000;
		Ext.MessageBox.wait('<div style="width:300px">'+(arguments[0] || '处理中')+'</div>','请稍后...');
		if(overTime>0){
			setTimeout(function(){Ext.MessageBox.hide();},overTime);
		}
	},
	done:function(){Ext.MessageBox.hide();},
	alert:function(){Ext.MessageBox.alert((arguments[1] || '温馨提示'),'<div style="width:'+(arguments[2]||300)+'px">'+(arguments[0] || '')+'</div>');},
	confirm:function(title,msg,yesFn,noFn){
		var yesFn = arguments[2] || function(){};
		var noFn = arguments[3] || function(){};
		Ext.MessageBox.confirm(title, msg, function(r){
			if (r == 'yes') yesFn();
			else noFn();
		});
	},
	get: function(){
		//var pData = arguments[1] || '';
		var pUrl  = arguments[0] || ''; //可选 参数
		var sFun  = arguments[2] || ''; //可选 参数
		var fFun  = arguments[3] || ''; //可选 参数
		var cfg   = arguments[4] || {}; //可选 参数
		Ext.Ajax.request(
			Ext.apply(
			{
				url:pUrl,
				//params:pData,
				success:function(response,opiton){
					if(sFun!==''){
						obj = Ext.util.JSON.decode(response.responseText);
						if(obj.NoAuth || false){alert('权限不足');}
						if(obj.LoginOverTime || false){location.href=location.href;}
						eval(sFun)(obj,response.responseText);
					}
				},
				failure:function(){
					if(fFun!==''){
						eval(fFun)(response.responseText);
					}
					//alert(response.responseText);
				}
			},cfg)
		);
	},
	a: function (config){
		config.id = (Ext.isObject(config.id)? (config.id) : (Ext.fly(config.id)) );
		config.fn = config.fn||'';
		config.id.onDestroy;
		var run = arguments[1]||(config.run || false);
		var SucFn = config.fn||'';
		var beforeFn = config.beforeFn ||'';
		var selecter="a"+(config.selecter||"");
		function runEvent(t){
			if(beforeFn!==''){beforeFn(t);}
			if(run) run(t);
			else Pub.get(t.href,'',function(r,rText){eval(SucFn)(r,t,rText);});
		}
		config.id.on('click',function(e,t){
				e.stopEvent();
				var tmp = (t.getAttribute('_confirm') || false) ;
				if(tmp) Pub.confirm( '请确认', tmp, function(){runEvent(t);} );
				else runEvent(t);
			},null,	{delegate:selecter}
		);
		config = null;
		delete config;	
	},
	submit: function (target){
		return this.form.submit(target);
	},
	tbar:function(){
		var json = arguments[0] || '';
		if(json!='')return json;
		else return [{text:'Add Something',tooltip:'Add a new row',iconCls:'add'},
					 '-',
					 {text:'Options',tooltip:'Blah blah blah blaht',iconCls:'option'},
					 '-',
					 {text:'Remove Something',
									tooltip:'Remove the selected item',
									iconCls:'remove'
					 }];
	},
	gridBbar:function(json){
		var ps = json.pageSize || 20;
			json.ds = json.ds||json.store;
		var msgtype = json.msgSimple || false;
		var msg = '{0} 到 {1}，共 {2}';
		if(msgtype)
			msg= '{0} 到 {1}，共 {2}';
		return new Ext.PagingToolbar({
			pageSize: ps,
			store:json.ds,
			displayInfo: true,
			displayMsg:msg,
			emptyMsg:"没有记录"
		});
	},
	string:{
		format : function(format,json){
	    	var json = json||{}
	    	return format.replace(/\{(\w+)\}/g, function(m, key){
			     return json[key]+'';
			});
	    },
		copy:function copy_code(copyText) 
		{ 
			if (window.clipboardData){window.clipboardData.setData("Text", copyText);} 
			var id = this.unique();
			new Ext.Window({
				title:"您的浏览器无法操作粘贴板，请按下 【Ctrl+c】",
				width:500, height:200,
				padding:1,
				id:id, layout:"fit",
				keys:[{ 
					key:'c',
					ctrl:true,
					fn:function(){
						Ext.getCmp(id).setTitle('已经成功复制到粘贴板');
						setTimeout(function(){Ext.getCmp(id).close();},500);
					}
				}],
				listeners:{show:function(){
					Ext.getCmp(id+'-field').focus(true,100);
					Ext.getCmp(id+'-field').focus(true,800);
				}},
				items:[{xtype:"textarea", id:id+'-field', value:copyText,selectOnFocus:true}]
			}).show();
			/*else { 
				var flashcopier = 'flashcopier';
				var swfPath=this.parent.src('[JSFW]')+'plugins/js/_clipboard.swf';
				if(!document.getElementById(flashcopier)){ 
					var divholder = document.createElement('div'); 
					divholder.id = flashcopier; 
					document.body.appendChild(divholder); 
				} 
				document.getElementById(flashcopier).innerHTML = ''; 
				var divinfo = '<embed src="'+swfPath+'" FlashVars="clipboard='+encodeURIComponent(copyText)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>'; 
				document.getElementById(flashcopier).innerHTML = divinfo; 
			} 
			alert('copy成功！');*/
		},
		random:function(){return Math.random();},
		unique:function(){ return (Math.random()+'').replace('.','D'); },
		delPre:function(str,pre){return 'R:E#PLI#C:E'+str.replace('R:E#PLI#C:E'+pre,''); },
		delSuf:function(str,pre){return str+'R:E#PLI#C:E'.replace(pre+'R:E#PLI#C:E',''); },
		ucwords:function(str) {
			  ''+str.toLocaleLowerCase();
			  return str.replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g,
				function(s){ return s.toLocaleUpperCase(); }
			  );
		},
		ucfirst:function(str){
			return (''+str).replace(/(^([a-zA-Z\p{M}]))/,
					function(s){return s.toLocaleUpperCase();}
			);
		},
		lc:function(s){return (s+'').toLocaleLowerCase();},//lowerCase
		uc:function(s){return (s+'').toLocaleUpperCase();},//upperCase
		parseObjectIndex:function aaa(str)
		{

			var start = arguments[1]||0;
			var arr = str.split('.');
			var re = /\d+/;
			
			for (var i = start; i < arr.length; i++) {
				arr[i] =  re.test(arr[i])? '['+arr[i]+']': '.'+arr[i];
			};
			str = arr.join('');
			return start==0? str.replace(/^\./,''): str;
		}
	},
	json:{
		encode:function(data){return Ext.util.JSON.encode(data);},
		decode:function(data){return Ext.util.JSON.decode(data);},
		toDs:function(v){
			var cfg = arguments[1]||{};//{head:{},tail:{}}
			var k,r = [];
			var i=0;
			v = [cfg.head||{},v,cfg.tail||{}];
			for(n=0;n<3;n++){
				for(k in v[n]){
					if(typeof(v[n][k])!='function'){
						r.push( [k,v[n][k]] );
					}
				}
			}
			return r;
		},
		buildHttpQuery:function (formdata, numeric_prefix, separator){
			function urlencode (str) {
				str = (str + '').toString();
				return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+'); ///'
			}
			var value,key,tmp = [];
			for(k in formdata){
				tmp.push( urlencode(k+'')+'='+urlencode(formdata[k]) );
			}
			return tmp.join(separator||'&');
		},
		keys:function(json){
			var tmp = [];
			for(var k in json){tmp.push(k);}
			return tmp;
		},
		values:function(json){
			var tmp = [];
			for(var k in json){tmp.push(json[k]);}
			return tmp;
		},
		map: function(json,fn){
			for(k in json){
				json[k] = fn(k);
				//if(typeof(cfg[k])!='undefined') r[k] = cfg[k];
			}
			return json;
		},
		//example 1: array_flip( {a: 1, b: 1, c: 2} );
		//returns 1: {1: 'b', 2: 'c'}
		flip:function (input) {
		  var key, tmp = {};
		  for (key in input) {
		  	//if(typeof(input[key])==='string') tmp[input[key]] = input[key];
		    if (!input.hasOwnProperty(key)) {continue;}
		    tmp[input[key]] = key;
		  }
		  return tmp;
		},
		diff:function(ps,pc){
			if(typeof(pc)==='string')pc = this.flip(pc.split(','));
			
			for(k in pc){
				ps[k]=null;
				delete ps[k];
			}
			return ps;
		},
		intersect:function(cfg,filter){
			if(typeof(filter)==='string')filter = this.flip(filter.split(','));
			var str,r = {};
			for(k in filter){
				if(typeof(cfg[k])!='undefined') r[k] = cfg[k];
			}
			return r;
		},
		init:function(p){
			//p = p||{};
			for(k in p){
				if(k!='parent' && Ext.isObject(p[k])){
					p[k].parent = p;//后赋值	
					this.init(p[k]);//先递归						
				}
			}
			return p;
		}
	},
	object:{
		diff:function(ps,pc){ return this.parent.json.diff(ps,pc); },
		intersect:function(cfg,filter){ return this.parent.json.intersect(cfg,filter); },
		flip:function(obj){	return this.parent.json.flip(obj); }
	},
	freeGrid : function (cfg){
		function changeToEditor(str){		
			if(str.replace('[=]','')!==str){
				var jsonCfg={height:40};							
				return new Ext.form.TextArea(jsonCfg);
			}else if(str.replace('[-]','').replace('[abc]','')!==str){
				var jsonCfg={height:40};							
				return new Ext.form.TextField(jsonCfg);
			}else if(str.replace('[123]','').replace('[no.]','')!==str){
				var jsonCfg={height:40};							
				return new Ext.form.NumberField(jsonCfg);
			}else if(str.replace('[combox]','')!==str){
				//var jsonCfg={height:40};						
				return Pub.ComboBox({isConfig:true,data:[[1,'是'],['','否']]});		
				//return new Ext.form.NumberField(jsonCfg);
			}
			return str;
		}
		cfg.column = cfg.column || 3;
		cfg.editor = cfg.editor || {};
		cfg.grid = cfg.grid || {};
		gridListeners = cfg.gridListeners ||{};
		deleteCfg = {};
		deleteCfg.gridListeners=null;
		deleteCfg.editor=null;
		var editSucc  = cfg.editSucc|| function(){};
		var eUrl = cfg.eUrl || false;
		deleteCfg.eUrl=null;
		if(eUrl) {			
			gridListeners.afteredit=function(e){
				if(e.value!=e.originalValue){
					Pub.post({'FieldName':e.record.id,'FieldValue':e.value,'OriginalValue':e.originalValue},eUrl,editSucc);
				}		
			};
		}else if(cfg.handler){
			gridListeners.afteredit=function(e){
				cfg.handler(e);
			};
		}
		var index,ds=[];
		//var value,field,editor;
		var rows = cfg.ds.length/cfg.column;
		var i=0,n=0;
		for(var k in cfg.ds){
			ds[i] = ds[i] || {value:{},field:{},editor:{}};
			index = cfg.ds[k].dataIndex ||  (cfg.ds[k][0] || false);
			if(index){
				ds[i].value[index]=cfg.ds[k].value ||      (cfg.ds[k][2] || '');
				ds[i].field[index]=cfg.ds[k].text ||      (cfg.ds[k][1] || '');
				if(cfg.ds[k].editor ||    (cfg.ds[k][3] || false)){
					ds[i].editor[index]=cfg.ds[k].editor ||      (cfg.ds[k][3] || '');
				}
				if(cfg.editor[index] || false){
					ds[i].editor[index]=cfg.editor[index];
				}
				if(ds[i].editor[index] || false){
					ds[i].editor[index] = new Ext.grid.GridEditor(changeToEditor(ds[i].editor[index]));
				}
			}
			n++;
			if(rows<=n){
				i++; 
				n =0;
			}
		}
		var disableEditField = cfg.grid.disableEditField || '';
		gridListeners.beforeedit=function(e){
			var field = e.record.data.name.split('--');
			field = field[1]||field[0];
			var disableEdit = ','+disableEditField+',';
			if(disableEdit ===disableEdit.replace(',!'+field+',','')){
				if( disableEdit != (disableEdit.replace(','+field+',','')).replace(',[ALL],','') ){
					e.cancel = true; 
					return false;
				}
			}
		};
		var items = [new Ext.grid.PropertyGrid({columnWidth:.0001})];
		for(i=0;i<ds.length;i++){
			items[(items.length)] = new Ext.grid.PropertyGrid(
			Ext.apply({
				columnWidth:Math.round((100/cfg.column))/100,
				autoScroll:true,
				propertyNames:ds[i].field || {},
				source:ds[i].value || {},
				border:false,
				viewConfig : {forceFit:true,scrollOffset:0},
				listeners : gridListeners,
				customEditors:ds[i].editor || {}
			},cfg.grid)
			
			);
		}
		deleteCfg.column=null;
		deleteCfg.grid=null;
		deleteCfg.ds=null;
		cfg = Pub.object.diff(cfg,deleteCfg);
		return Ext.apply({
			layout:'column',
			autoScroll:true,
			items:items
		},cfg);
	},
	line:function(cfg){
		cfg.width = cfg.width || '1px';
		cfg.width = cfg.height || '100%';
		cfg.color = cfg.color || '#99BBE8';
		return '<div style="position:absolute; height:'+cfg.height+'; width:'+cfg.width+'; background:'+cfg.color+';right:20px; border-left:solid #FFF 1px; border-right:solid  #FFF 1px;z-index:100"></div>';
	},
	json2Ds:function(v){ return this.json.toDs(v); },
	grid:function (config)
	{
		config = Ext.apply({
			stripeRows:true,
			loadMask:true
		},config);

		var isRw = config.rw || false;
		var parmaryId = config.prId =config.prId || 'id';
		var eUrl = (config.eUrl||'?');
		var editSucc = (config.editSucc||'');
		var addSucc = (config.addSucc||'');
		var events  = (config.events||{});
		var postField = config.postField || {};config.postField=null;
			postField = typeof(postField)==='string'? [postField] : postField;
		delete config.postField;
		delete config.prId;
		delete config.rw;
		delete config.eUrl;
		config.editSucc=null;delete config.editSucc;
		config.addSucc=null;delete config.addSucc;
		config.events=null;delete config.events;
		//if(config.title || config.title=='')config.header=false;
		//Ext.applyIf(config||{},{})
		var viewKey = false;
		if(config.viewConfig && (config.viewConfig.allowControlText || false) ){
			viewKey = 'viewConfig';
		}else if(config.view && (config.view.allowControlText || false) ){
			viewKey = 'view';
		}
		if(viewKey){
			config[viewKey].templates = config[viewKey].templates || {};
	    	config[viewKey].templates.cell =new Ext.Template(   
	            '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} x-selectable {css}" style="{style}" tabIndex="0" {cellAttr}>',   
   					'<div class="x-grid3-cell-inner x-grid3-col-{id}" {attr}>{value}</div>',   
   				'</td>'    
	    	);
	    	delete config[viewKey].allowControlText;
		}
		if(!isRw){
			config.listeners = Ext.apply((config.listeners||{}),events);
			return new Ext.grid.GridPanel(config);
		}else{
			config.listeners = Ext.apply(
				(config.listeners||{
					"afteredit":function(e){
						if(e.value!=e.originalValue){
							if(e.record.data[parmaryId] && (e.record.data[parmaryId]=='*'||e.record.data[parmaryId]=='0*')){
								if(addSucc!='editSucc'){
									editSucc = addSucc;
								}
							}
							var post={};
							if(postField){
								for(k in postField){
									if(typeof(postField[k])==='string')post[postField[k]] = e.record.data[postField[k]] || '';
								}
							}
							Pub.post(
								Ext.apply(post, {
									'FieldName' : e.field,
									'FieldValue' : e.value,
									'OriginalValue' : e.originalValue,
									'id' : (e.record.data[parmaryId] || '')
								}),
								eUrl, editSucc
							);
						}					
					}
				}),events
			);
			config.clicksToEdit = config.clicksToEdit|| 1;
			return new Ext.grid.EditorGridPanel(config);
		}
		//config.store.load();
	},
	win:function(config)
	{
		var me = this;
		var win=false,winId = Math.random();;
		if(config.id){
			winId = config.id;	
			win = Ext.getCmp(winId);
		}
		config.animateTarget = config.animateTarget || (config.aEl || 'xxx-default-aEl');
		config.listeners = Ext.apply({
			beforeclose:function(cmp){
				if(cmp.__diyAllowClose || false){
					return true;
				}else{
					cmp.__diyAllowClose = true;
					setTimeout(function(){me.animClose(cmp.id);},10);
					return false;
				}
			}
		},config.listeners||{});

		if(!win){
		 	win = new Ext.Window(
				Ext.applyIf(
					config||{},
					{
						title:"新窗口",
						maximizable:true,
						animCollapse:true,
						width:580,
						height:400,
						shadow:false,
						//border:false//,
						//items:{}
						//buttonAlign:"center"
						constrain:true,
						id:winId
					}
				)
			);
		}
		win.show();
		return win;
	},
	httpBuildQuery:function (json, prefix, separator) {
		return this.json.buildHttpQuery(json, arguments[1]||false, arguments[2]||false);
	},
	
	frameWin:function(cfg){
		var me = this;
		var url = (cfg.url || '')+ ((cfg.param||false)? '&'+me.json.buildHttpQuery(cfg.param):'');
		cfg.url = null; delete cfg.url;delete cfg.param;
		cfg.id  = cfg.id||Math.random();
		//encodeURIComponent
		cfg.refresh = function(param,flushUrl){
			flushUrl = flushUrl || cfg.url;
			flushUrl = url+'&'+param;
			Ext.getDom(id+'-print').src = url+'&'+me.json.buildHttpQuery(param)+'';
		};		
		cfg.html='<iframe class="xxx-loading" id="'+id+'-print" name="'+id+'-print" src="'+url+'" width="100%" height="100%" frameborder="0"></iframe>';
		return Pub.win(cfg);	
	},
	printView:function(cfg){
		var id = cfg.id||Math.random();
		Pub.win({
			id:id,
			title:cfg.title||'打印预览',
			tbar:[{xtype:"button",icon:Pub.ico('print'),text:"打印",handler:function(){Pub.print(id+'-print');}}],
			width:800,
			html:'<iframe class="xxx-loading" id="'+id+'-print" name="'+id+'-print" src="'+cfg.url+'" width="100%" height="100%" frameborder="0"></iframe>'
		});
	},
	print:function(win){
		//focus();
	    document.getElementById(win).contentWindow.window.print();
	},
	load:function(ds,id){
		var cfg = arguments[2] || {};
		var cmp = Ext.getCmp(id);
		cmp.disable();
		if(cfg.fun || false){
			cfg.callback = function(r,c,s){
				cfg.callback(r,c,s);
				cmp.enable();
			};
		}else{
			cfg.callback = function(){cmp.enable();};
		}
		ds.load(cfg);
	},
	form:{
		submit:function(cfg){

			//cfg.url   = cfg.url || ''; //可选 参数
			//cfg.succ  = cfg.succ || ''; //可选 参数
			//cfg.error = cfg.errorRun || ''; //可选 参数
			//if(Ext.isString(cfg.form))var form = Ext.get(cfg.form);
			//else
			var form = cfg.form;
			    form = typeof(form)==='string'? Ext.getCmp(form): form;

			var success = cfg.success || false;
			var failure = cfg.failure || false;
			
			form.getForm().submit(Ext.apply(cfg,{
			    url:cfg.url,	
			    timeout:cfg.timeout||30,
			    success: function(form, action) {
					if(success){
						eval(success)(form, action);
					}else{
						if(action.result){
					  		Ext.Msg.show({
								title:'提示?',
								msg: action.result.message || (action.result.msg || ''),
								buttons: Ext.Msg.OK,
								animEl: 'elId',
								minWidth:280,
								icon: Ext.MessageBox.INFO
							});
						}
					}
			    },
			    failure: function(form, action) {
			    	if(failure){
						eval(failure)(form, action);
					}else{					
						if(action.result){
					  		var msg = action.result.message || (action.result.msg || '');
						  		Ext.Msg.show({
								title:'注意：',
								msg: msg,
								buttons: Ext.Msg.OK,
								animEl: 'elId',
								minWidth:280,
								icon: Ext.MessageBox.ERROR
							});
						}else{
							//var msg = '请求无响应，请检查您的网络是否正常';
						}
						
				   }
			    }
			}));
			return true;
		},
		field:function(cfg){
			var p;
			if(typeof(cfg)==='string'){
				p = cfg;
				cfg = {};
			}else{
				p = (cfg.field || cfg.type); delete cfg.field; delete cfg.type;
			}
			p = p.toLocaleLowerCase();
			switch(true){
				case (p==='-' || p==='text'):return new Ext.form.TextField(cfg);
				case (p==='123' || p==='number'): return new Ext.form.NumberField();
				case (p==='date'):return new Ext.form.DateField(cfg);
				case (p==='=' || p==='textarea'):return new Ext.form.TextArea();
				case (p==='list'): 
					if(cfg.url||false){
						return Pub.comboBoxRemote(cfg);			
					}else{
						cfg.isConfig = true;
						return Pub.ComboBox(cfg);
					}
				
			}
			if(p==='upload'){
				var url = (cfg.uploadUrl || ''); delete cfg.uploadUrl;
				return new Ext.form.TriggerField(Ext.apply({
					anchor:"100%",
					triggerClass:'extend-x-form-up-trigger',
					onTriggerClick : function () {
						var position = this.getPosition();
						Run.winUpload({
							url : url,
							x:position[0],
							animateTarget:this.id,
							y:position[1]+23,
							modal : true,
							title : (cfg.uploadTitle || '文件上传')
						});
					}
				},cfg));
			}
		}
	},
	formField:function(cfg){return this.form.field(cfg);},
	ComboBox: function()
	{
		var data,config = arguments[0]||'';
		var isConfig = config.isConfig||(config.IsConfig || false);
		if(isConfig){
			config.IsConfig = null;delete config.IsConfig;
			config.isConfig = null;delete config.isConfig;
			data = config.data||{};delete config.data;
		}else{
			data = (config == ''? [[1,'是'],[0,'否']] :config);
			config = {value:(arguments[1]||'')};
		}
		if(Ext.isString(data)){
			data = data.split(",");
			for(var k in data){
				data[k] = [k,data[k]];
			}
		}
		var displyF = 'text';
		var valueF  = 'value';
		
		if(config.multiSelect || false){
			config.onSelect = function(record, index){
				var me = this;
				var displyF = this.displayField;
				var valueF  = this.valueField || this.displayField;
            	if(me.fireEvent('beforeselect', this, record, index) !== false){
                   record.set('check',!record.get('check'));
                   var str = [];//页面显示的值 
                   var strvalue = [];//传入后台的值 
                   this.store.each(function(rc){
                       if(rc.get('check')){
                           str.push(rc.get('text'));
                           strvalue.push(rc.get('value'));
                       }
                   });
                   //this.setValue(str.join());
                   this.setValue(strvalue.join());
                   //this.value = strvalue.join();
                   //Ext.getDom(me.id).value=str.join();
                   this.fireEvent('select', this, record, index);
               }//record.set('check','true')); 默认勾选多个下拉项呢
            };
			config.tpl = '<tpl for="."><div class="x-combo-list-item"><span>'+
						 '<input type="checkbox" {[values.check?"checked":""]} value="{'+valueF+'}" />'+
						 '</span><span >{'+displyF+'}</span></div></tpl>';
		}
		return new Ext.form.ComboBox(Ext.apply({
			store:new Ext.data.SimpleStore({
				fields: ['value','text'],
				data:data
			}),
			//reload:function(dsData){this.loadData(dsData);}
			valueField:valueF,      //传送的值
	        displayField:displyF,     //UI列表显示的文本
			triggerAction:'all',
			mode:'local'//,
			//typeAhead: true
			},config)
		);
	},
	comboBoxRemote:function(config){
		var LoadUrl = config.url;delete config.url;
		var root = config.root||'';config.root=null;delete config.root;
		config.displayField  = config.displayField||'text';
		config.valueField = config.valueField||'value';
		return new Ext.form.ComboBox(Ext.apply({
	      	name:'identity',
	      	allowBlank : false,
	      	mode:'remote',
	      	triggerAction:'all',
	      	emptyText:'请选择...',
	      	store:new Ext.data.JsonStore({
	        	url:LoadUrl,
	        	fields:[config.valueField,config.displayField],//new Ext.data.Record.create( ['text', 'value']),
	        	root:root
	    	}),
	    	valueField:config.valueField,
	    	displayField:config.displayField
			},config)
		);
	},
	NumToDate:function(val)
	{
		if(Ext.isNumber(val)){
				return val.substring(0,4)+'-'+val.substring(4,6)+'-'+val.substring(6,8);
		}else return val;
	},
	addTab:function(config){
	    	config['id'] = config.id || Math.random();
	    	config['items'].renderTo=config.id;
	    	//config['items'].width=get.;
	        tabs.add(
	          	Ext.applyIf(config||{},{
	          		layout:"fit",
	          		//autoWidth:true,
	          		//style:'height:100%',
		            title: '项目列表',
		            iconCls: 'tabs',
		            items:{html:'CREATE TAB FINISH'},
		            closable:true,
		            bodyStyle:"background:#5a83b9 url("+Pub.src('---Image/bg-workpalce.png')+") repeat-x",
		            bbar:['-']		            
		     	})
		     ).show();
	},
	date:function() 
	{
		var days = arguments[1] || 0;
		var date = new Date(); 
		if( days != 0 ){
			date.setDate(date.getDate()+days);//获取days天后的日期
		}
		return date.format(arguments[0] || 'Y-m-d');
	},
	dsFromat:function(data){
		var r=[],i=0;
		for(var k in data){
			r[i] = [k,data[k]];
			i++;
		}
		return r;
	},
	loadCls:function(cls,fn){
		var me = this;
		me.include(me.clsToFile(cls), function(){me.relyRun(fn, (typeof(cls)=='string'?[cls]:cls), 200,30);} );
		//me.include(me.clsToFile(cls), fn );
	},
	include:function (src,fn) 		 
	{
		var noCheck = (arguments[2]|| false);
		var src = ( typeof(src)==='string'? [src] : src );
		if(!noCheck  &&  src.length>0){
			var tmp = [];
			var i=0;
			for(var k in src){
				if(typeof(src[k])==='string' && !(Ext.select('head script[src*='+src[k]+']').elements[0] || false)  ){				
					tmp[i]=src[k]+'?_cd='+this.random; i++;
				}
			}
			src = tmp;
		}
		
		if(src.length<1){
			return fn();
		}else{
			var loadStatus = Ext.getDom('body-load-module-status');
			if(loadStatus || false){
				loadStatus.style.display='block';
			}else{
				var html = '<div align="center" style="position:absolute; z-index:99999; width:100%; margin-top:200px" id="body-load-module-status">'+
					'<div style="border:#99BBE8 double 3px; width:180px; font-size:12px; padding:10px; background:#EDEFED"><span class="loading-indicator">&nbsp;</span>正在加载所需组件.请稍后...</div>'+
				'</div>';
				Ext.get(Ext.select('body')).insertHtml('beforeEnd',html);
				loadStatus = Ext.getDom('body-load-module-status');
			}
			try{
				var onload = function(){
					setTimeout(function(){loadStatus.style.display = 'none';},1000);
					fn();				
				};
				if(Ext.Loader.loadScript || false)Ext.Loader.loadScript({onLoad:onload,url:src});
				else Ext.Loader.load(src,onload);
			}catch(exception){setTimeout(function(){loadStatus.style.display = 'none';},1000);}
			return ;
		}
	},
	stateRun:function(p,run){
		var me = this;
		var importFiles = (arguments[2]||'').toLowerCase();
		var pLower = ('_'+p+'_').replace(/([A-Z])/g,' $1').replace(/[^\(\)\w]+/g,'_').toLowerCase();
			pLower = pLower.replace(/\(/g,'_(').replace(/\)/g,')_').replace(/_+/g,'_');
		var i = 0;
		var loadFile = new Array();
		var jsPath = (Init.path.tplPublic || '')+'Js/';
		Ext.each(
			(Init.jsList||[]),
			function(v,k){
				var tmp = ':'+v.toLowerCase()+'_';
				var ok = ( tmp.replace(':'+importFiles+'_','') != tmp );
				
				var lower= ('_'+v+'_').replace(/\W+/g,'_').toLowerCase();
				var congruent = '('+( lower.substr(1,lower.length-2) )+')';				
				if(ok || pLower.replace(lower,'') !== pLower || pLower.replace(congruent,'') !== pLower){
					loadFile[i] = v;
					i++;
				}
			}
		);
		
		var n=0,allowInclude=[];
		loadFile = me.arrayUnique(loadFile);
		//alert(p+"\n"+pLower+"\n"+uneval(loadFile));	
		for(i=0;i<loadFile.length;i++){
			if(!(Ext.select('head script[src*=/'+loadFile[i]+'.js]').elements[0] || false)){
				allowInclude[n] = jsPath+loadFile[i]+'.js';
				n++;
			}
		}

		var len = allowInclude.length;
		
		//alert(p+"\n"+pLower+"\n"+uneval(allowInclude));	
		function recursion(i){
			//alert(i+'--------'+allowInclude[i]);
			me.include(allowInclude[i],function(){
				if((i+1)>=len){	eval(run)(); return;}
				else{ recursion(i+1); return;}
			});
		}
		if(len<1){run();}
		else{recursion(0);}
		
	},
	run:function(p){
		var run = arguments[1] || function(){eval('new '+p+'()');};
		
		if( typeof(eval(p))=='function' ){	
			run();
		}else{
			Pub.stateRun(p,run);
		}
	},
	download:function(cfg)
	{/*alert(uneval(cfg));*/
		cfg.post = cfg.post || (cfg.param || {});
		cfg.post['X-REQUEST-WITH-X']='download-and-export';
		var val;
		var str = '<form id="pub-download_temp-form" name="pub-download_temp-form" method="post" action="'+(cfg.url||'')+'" target="pub-download_temp-submit-iframe">';
		for(var k in cfg.post){
			val = (cfg.post[k]+'').replace(/"/g,'&quot;');/*"转字符串对象*/
			str += '<input name="'+k+'" type="hidden" value="'+val+'" />';
		}
		str += '</form><iframe id="pub-download_temp-submit-iframe" name="pub-download_temp-submit-iframe" src="" width="0" height="0" frameborder="0"></iframe>';
		var cmp = Ext.getDom('pub-download_temp-div-cmp')||false;
		if(!cmp){
			str = '<div style="display:none" id="pub-download_temp-div-cmp">'+str+'</div>';
			Ext.select('body').insertHtml('beforeEnd',str);
		}else{
			cmp.innerHTML=str;
		}
		document['pub-download_temp-form'].submit();
	},
	fitClient:{
		width:function(){
			var max    = arguments[0] || false;
			var rate   = arguments[1] || 0.8;
			var total  = document.body.clientWidth;  
			return total>max ? max: (total*rate);
		},
		height:function(){
			var max    = arguments[0] || false;
			var rate   = arguments[1] || 0.8;
			var total  = document.body.clientHeight;  
			return total>max ? max: (total*rate);
		}
	},
	tableBox:function(cfg){
		cfg = Ext.apply({
			boxWidth:40,
			boxHeight:40,
			rows:1,
			cells:1,
			id:Math.random()+''.replace('.','_'),
			data:[]	
		},cfg);
		
		var n=0; 
		var w = cfg.width = cfg.width || cfg.cells*cfg.boxWidth;
		cfg.boxWidth = w/cfg.cells;
		var data,item = '';
		var boxHandler = cfg.boxHandler || function(){};
		for(var i=1;i<=cfg.rows;i++){
			item +='<tr>';
			for(var c=1;c<=cfg.cells;c++){
				data = cfg.data || ['',''];
				item += String.format('<td class="pub-table-box-item" style="width:{0}px; height:{1}px;" _sign="{2}">{3}</td>',cfg.boxWidth,cfg.boxHeight,data[0],data[1]);
				n++;
			}
			item +='</tr>';
		}
		var str = '<div class="pub-table-box"><table width="100%" border="1" align="center" cellspacing="0" class="pub-table-box-table" style="width:'+(w>1? w+'px': w+'%')+'" >'+item+'</table></div>';
		return {
			html:str,
			listeners : {
				afterrender : function () {
					//Ext.fly(cfg.id).on('click', function (e, t) {
					//	var sign = t.getAttribute('_sign');
					//	boxHandler(sign,t);
					//});
				}
			}		
		};
	},
	ppt : function (pptist) {
		var cfg = Ext.apply({
			urlPath:'',
			urlThumPath:'',
			addFn:false
		},arguments[1] || {});
		var addFn = cfg.addFn || false;
		//var defalutView = cfg.defaultView || {}; delete cfg.defaultView;
		var _diIndex = 0;
		function imgProcess(p) {
			var thumSize = cfg.thumSize || [50,50];
			var thum = '<ul class="pub-fn-ppt-thum">';
			var img = {};
			for (var key in p) {
				if(p[key] && typeof(p[key])!='function'){
					var cssClass = (_diIndex==key ? 'thum-selected': '');
					img[key] = typeof(p[key]) === 'string' ? [p[key], p[key]] : p[key];
					img[key][1] = img[key][1] || img[key][0];
					thum += '<li pptItem="ppt_item" class="'+cssClass+'"><span class="pub-mark"></span>'+
							'<img style="height:'+thumSize[0]+'px;width:'+thumSize[1]+'px" src="' +cfg.urlThumPath + img[key][0] + '" '+
							'onerror="this.onerror = null;this.src=\''+(Init.path.errorImg||'')+'\';" '+
							'ppt:img="'+cfg.urlPath + img[key][1]+'" ppt:thum-key="'+key+'" class="hand"/></li>';
				}
			}
			thum += (addFn && typeof(addFn) === 'function')
				? '<li><img name="-ADD-IMG-" src="' + Pub.ico('add2-50x50') + '"  style="height:'+thumSize[0]+'px;width:'+thumSize[1]+'px" '
				+ 'lang="" class="hand"/></li>' : '';
			var defaultImg = (img[_diIndex] || false) ? (img[_diIndex][1] || (img[_diIndex][0] || '')) : '';
			thum += '</ul>';
			return {thum : thum, img : img,front : defaultImg};
		}
		var imgResult = imgProcess(pptist);
		var id = (cfg.id || Math.random()+'');
		var oImgId = id + '-img-o';
			var imgList = new Ext.Container({
				autoEl : "div",
				region : "south",
				id : id + '-img-list',
				style:"float:left;position:relative;",
				cls : "pub-ppt-fn",
				html : '<div id="' + id + '-img-list-thumcmp" style="position:absolute;left;0;bottom:0;">' + imgResult.thum + '</div>',
				//height : 60,
				autoHeight:true,
				listeners : {
					beforedestroy : function () {
						imgList.purgeListeners();
					},
					afterrender : function () {
						Ext.fly(id + '-img-list').on('contextmenu', function (e, t) {
							var indexId = t.getAttribute('ppt:thum-key');							
							var cmp = Ext.getCmp(cfg.id);
							var tagName = (t.name || '');
							if (tagName.replace('-ADD-IMG-', '') == tagName) {
								new Ext.menu.Menu({
									listeners:{hide:function(e){e.destroy();}},
									items : [{
											text : '设为主视图',
											disabled: (indexId === _diIndex),
											hidden: (cfg.setDefaultViewFn || false) ? false :true,
											handler : function (itemNode) {												
												Ext.each(
													Ext.query('li[pptItem=ppt_item]'),
													function(v){v.className="";}
												);
												Ext.fly(t).parent("li").addClass("thum-selected");
												_diIndex = indexId;
												if (cfg.setDefaultViewFn || false) {
													cfg.setDefaultViewFn(t,indexId, cmp);
													this.hide();
												}
											}
										}, {
											text : '删除',
											disabled: (indexId === _diIndex),
											hidden: (cfg.deleteFn || false) ? false :true,
											handler : function () {
												if (cfg.deleteFn || false) {
													cfg.deleteFn(t,indexId,cmp);
												}
											}
										}
									]
								}).showAt(e.getXY());
							}
							e.stopEvent();
						}, null, {
							delegate : 'img'
						});
						Ext.fly(id + '-img-list').on('click', function (e, t) {
							var oSrc = t.getAttribute('ppt:img');
							var tagName = (t.name || '');
							if (tagName.replace('-ADD-IMG-', '') != tagName) {
								if (addFn && typeof(addFn) == 'function')
									addFn();
							} else {
								Ext.getDom(oImgId).src = oSrc || t.src;
							}
						}, null, {
							delegate : 'img'
						});
					}
				}
			});

		return new Ext.Panel(Ext.apply({
				//title : "图片",
				width : 400,
				height : 250,
				layout : "border",
				region : "east",
				reload : function (i,def) {
					_diIndex = def;
					i = i || imgResult.img;
					var r = imgProcess(i);
					var dom = Ext.getDom(id + '-img-list-thumcmp');
					if(dom || false)dom.innerHTML = r.thum;
					//Ext.getDom(oImgId).src = t.front;
				},
				addItem : function(file,index){
					imgResult.img[index] = file;
					this.reload(imgResult.img,_diIndex);
				},
				items : [{
						xtype : "container",
						autoEl : "div",
						region : "center",
						html : '<table width="320" border="0" align="center"><tr><td height="230">'
						 + '<img id="' + oImgId + '" src="' + imgResult.front + '" width="320px"/>'
						 + '</td></tr></table>'
					}, imgList
				]
			}, cfg));
	},
	//selectedFn:function(v,t){},
	//value:'',
	//msg:'',
	//data:{}
	switchGroup:function(cfg)
	{
		var scope = this;
		cfg.data = cfg.data||{};
		var id = cfg.id||Math.random();

		var value = cfg.value || "DEFAULT:0";
		if(typeof(value)==='object' && value.url||false){
			var valueSrc = value.url;
			setTimeout(function(){ 
				var cmp = Ext.getCmp(id)||false;
				scope.http.get(valueSrc,'',function(r){
					if(cmp && (r.value||false)) cmp.reelect(r.value,function(){});
				});
			},1500);
			value=false;
			cfg.value= value;
		}
		
		
		var item = '',i=0;
		for(k in cfg.data){
			var selected=(value==k || value==='DEFAULT:'+i)? ' selected':'';
			item += '<td switch:key="'+k+'" class="hand '+selected+'" name="switchGroup" style="'+(cfg.itemStyle||'')+'">'+cfg.data[k]+'</td>';
			i++;
		}
		var html = '<div class="pub-switchgroup-fn"><table title="'+(cfg.msg||'')+'" class="pub-switchgroup-fn-cmp" id="'+id+'-tab'+'" height="20" border="0" '
				 + 'cellspacing="0">'
				 + '<tr title="'+(cfg.msg||'')+'" >'+item+'</tr></table></div>';
		return new Ext.Container({
			html:html,
			id:id,
			reelect:function(selVal,callBack){
				var me = this;
				var t = {};
				var e = Ext.fly(id+'-tab').select('td');
				e.each(function(el,v,index){							
					el.removeClass('selected');
					if(el.getAttribute('switch:key')===selVal){
						el.addClass('selected');
						t = el;
					}
				});
				if(callBack || false) eval(callBack)(selVal,t,me);
				else cfg.selectedFn(selVal,t,me);
			},
			listeners:{
				'afterrender':function(cmp){
					if(typeof(value)==='function'){
						value(cmp);
					}
					var cmp = this;
					Ext.fly(id+'-tab').on('click', function(e,t){
						var tVal = t.getAttribute('switch:key');
						cmp.reelect(tVal);						
					},null,{delegate:'td'});					
				}
			}
		});
	},	
	customCfg:function(label,type){
		if(arguments[1]||false){
			Init.customCfg.set(label,arguments[1]);
		}
		return Init.customCfg.get(label);
	},
	runFn:function(fn,arg){
		var exp = [];
		for(var i=0;i<arg.length;i++){
			exp[i] = 'arg['+i+']';
		}		
		eval(fn+'('+ exp.join(',') +')');
	},
	shortcutKey:function(key,cfg){
		key = key=='ENTER'? Ext.EventObject.ENTER :key;
		cfg = typeof(cfg)==='function'? {fn:cfg} : cfg;
		return Ext.apply({ 
			key:key,
			ctrl:true,
			fn:function(){},
			defaultEventAction: "stopEvent" ,
			stopEvent:true,
			scope:this 
		},cfg);
	},
	animClose:function(id){
		id = id+'';
		var random = (Math.random()+'_');
		//rm = random.substr(5,1);
		rm2= random.substr(4,1);
		//var anchor=['tl','t','tr','l','c','r','bl','b','br','r']
		var anchor=['r','r','r','l','l','l','t','t','b','b'];
		Ext.fly(id).ghost(anchor[rm2],{callback:function(){
			Ext.getCmp(id).close();
		}});
	},
	chart:{
		columnChart:function(cfg){
			cfg = cfg||{};
			var fields = [cfg.xAxis.field||'x',cfg.yAxis.field||'y'];
			if(arguments[1] || false) var chartDs =  arguments[1];
			else var chartDs =  new Ext.data.JsonStore({
				fields: fields,
				url:cfg.dataUrl || false
			});
			
			return Ext.apply({
				title:false,
				closable:false,
				getStore:function(){return chartDs;},
				reload:function(data){chartDs.loadData(data);},		
				items:[{
					xtype: 'columnchart',
					store: chartDs,
					yField: fields[1],				
					url: Init.path.JSFW+'resources/charts.swf',
					xField: fields[0],
					xAxis: new Ext.chart.CategoryAxis(cfg.xAxis),
					yAxis: new Ext.chart.NumericAxis(cfg.yAxis),
					extraStyle: {
					   //xAxis: {labelRotation: -45}
					}
				}]
			},cfg);
		}
	},
	isExists:function(id){
		var c = Ext.getCmp(id) || false;
		var fn = arguments[1] || false;			
		if(c){
			if(!fn){
				if(c.isSysWin || false) createSysWin(c);
				else c.show();
			}else fn(c);
			return true;
		}
		return false;
	},
	Component:{},
	c : {
		mousepress : function (cmp, longPressFn, clickFn) {
			var me = this;
			var longPressFn = arguments[1] || false;
			var clickFn = arguments[2] || false;
			var longPressTime = arguments[3] || 1000;
			var el = Ext.fly(cmp.id);

			var MOUSEDOWNED = false;
			
			el.on('mousedown', function (e) {
				//Pub.log(e);
				if(e.button===0){
					//me.parent.log('test::mousedown');
					var rand = Math.random() + '';
					MOUSEDOWNED = rand;
					setTimeout(function () {
						if (MOUSEDOWNED === rand) {
							MOUSEDOWNED = false;
							if (longPressFn)longPressFn();
						}
					}, longPressTime);
				}
			}, cmp);

			el.on('mouseup', function (e) {
				if(e.button===2){
					if (longPressFn)longPressFn();
					MOUSEDOWNED = false;
				}else if (MOUSEDOWNED) {					
					MOUSEDOWNED = false;
					if (clickFn)
						clickFn();
				}
			}, cmp);

		}
	},
	style:{
		color:function(str,color){ return '<span style="color:'+color+'">'+str+'</span>'},
		red:function(str){return this.color(str,'red');}
	}
}.init();
//Ext.onReady(function(){
	//-----------------------------------------------------------------------------
Run.winLoad = function (config)
{
	config = config||{};
	var url = config.url||'';delete config.url;
	Pub.win(Ext.applyIf(
	config||{},
	{
		title:config.title||"新建窗口",
		autoHeight:true,
		autoWidth:true,
		maximizable:false,
		autoLoad:{url:url,scripts:true} 
	}
	));
};
Run.LogOut = function ()
{
	Run.winLoad({title:"正在注销 请稍候",url:Pub.url('Public/logout')});
};
//-----------------------------------------------------------------------------------
function test_test_test(t){
	//getAttribute
	var test = t.getAttribute('diy_in_over');
	
	alert(t.getAttribute('diy_in_over'));
}
Ext.namespace('Ext.ux','Ext.ux.plugins');
Ext.MyFormContainer=Ext.extend(Ext.Container ,{
xtype:"container",
	autoEl:"div",
	width:"",
	height:"",
	layout:"hbox",
	initComponent: function(){
		this.items=[
			{
				xtype:"textfield",
				fieldLabel:"标签"
			},
			{
				xtype:"button",
				text:"我的按钮"
			}
		];
		Ext.MyFormContainer.superclass.initComponent.call(this);
	}
});

Ext.ux.plugins.textFieldToolMenu = function (cfg) {
	var tool = cfg.tool;delete cfg.tool;
	var position = cfg.position || [];delete cfg.position;
	this.init = function (field) {
		function toolList(p) {
			var toolCfg = arguments[1] || {};
			if (p === 'color') {
				return {
					text : "颜色",
					icon : Pub.ico('color'),
					menu : new Ext.menu.ColorMenu({
						listeners : {
							select : function (palette, color) {
								field.setValue('color:#' + color);
							}
						}
					})
				};
			} else if (p === 'textfield') {
				return new Ext.Container({
					//xtype:"container",
					autoEl:"div",
					icon : Pub.ico('edit'),
					items:new Ext.form.TextField({						
						style:'width:86%',
						value:field.getValue()||'',
						listeners : {
							//"afterrender":function(e){e.focus()},
							//"keydown":function(t){},
							"focus":function(t){t.setValue(field.getValue());},
							"change":function(t,v){field.setValue(v);}
						}
					})
				});
			} else if (p === 'upload') {
				var restorer = toolCfg.restorer || function(v){return v;};
				return {
					text : "图片",
					icon : Pub.ico('img'),
					menu : new Ext.menu.Menu(
						Run.uploadPanel(Ext.apply({
								plain : true,
								style : "padding:0px;",
								//url:
								width : 600,
								itemCfg : {
									afterSuccessFn : function (file, info) {										
										field.setValue(restorer(info.file));
									}
								}
							}, toolCfg)))
				};
			} else return {};
		}
		
		field.on("focus", function (obj) {
			var cTool = [];
			for (k in tool) {
				if (tool[k] === 'textfield' || tool[k] === 'color') {
					cTool[k] = toolList(tool[k]);				
				} else if (tool[k].xtype === 'upload') {
					//delete tool[k].xtype;
					cTool[k] = toolList('upload',tool[k]);
					delete cTool[k].xtype;
				} else {
					cTool[k] = tool[k];
				}
			}
			var box = obj.getBox();	
			position[0] = position[0] || 0;
			position[1] = position[1] || box.height;
			new Ext.menu.Menu(Ext.apply({				
				width : 120,
				items : cTool,
				shadow :false,
				listeners : {hide : function (e) {
					//确保事件完成后销毁
					setTimeout(function(){e.destroy();},600);
				}}
			},cfg)).showAt([box.x+position[0],box.y+position[1]]);
		});
	};
};
Ext.ux.plugins.textFieldToolBar = function (cfg) {
	var me=this;
	var tool = cfg.tool;delete cfg.tool;
	this.init = function (field) {
		var allowBlur = false;
		var random = Math.random() + '_id';
		field.on("blur", function (obj){
			if(allowBlur){
				allowBlur = false;
				return true;
			} //本来是下面一句徕控制的
			//if( Ext.getDom(random).getAttribute('_overstatus')==='yes' ){}
			else{
				//obj.focus();
				return false;
			}
		});
		field.on("render", function (obj) {			
			Ext.DomHelper.insertHtml(
				'afterEnd', obj.el.dom, 
				' <div _overstatus="no" '+
				' onmouseover="this.setAttribute(\'_overstatus\',\'yes\');" '+
				' onmouseout="this.setAttribute(\'_overstatus\',\'no\');" '+
				' style="margin-top:1px;" id="' + random + '"></div>'
			);
			function toolItelList(){
				var list = {
					color : {
						xtype : "button",
						text : "",
						//applyTo : random,
						icon : Pub.ico('color'),
						menu : new Ext.menu.ColorMenu({
							listeners : {
								select : function (palette, color) {
									//field.show();
									//field.focus();
									field.setValue('color:#' + color);
									
								}
							}
						})
					},
					uploadImg : {
						xtype : "button",
						icon : Pub.ico('img'),
						applyTo : random,
						menu : new Ext.menu.Menu(
							Run.uploadPanel({
								plain : true,
								style : "padding:0px;",
								width : 600
							}))
					}
				};
				var r=[],i=0;
				for(k in tool){
					if(tool[k] || false){
						if(list[k] || false){
							r[i] = tool[k];
						}
						r[i]   = Ext.apply((list[k]||{}),tool[k]);
						r[i+1] = '-';
						i+=2;
					}
					r[i+1] = '->',
					r[i+2] = {xtype:'button',icon:Pub.ico('cancel'),handler:function(){allowBlur=true;}};
				}
				return r;
			}
			var toolbar = new Ext.Panel({
				style:"border-bottom:0px;",
				renderTo : random,
				
				layout : "fit",					
				items:[{
					xtype:"toolbar",
					//layout: {overflowHandler: 'Menu'},
					height:27,
					//autoWidth:true,
					flaoting:true,
					style:"border-bottom:0px;",
					items:toolItelList()
				}]
			});
			toolbar.show();
		});
		/*field.on("beforedestroy", function (obj) {
			var button = Ext.query("[class=rightShowText]", obj.el.dom.parentNode)[0];
			Ext.removeNode(button);
		})*/
	};
};
Ext.ux.plugins.htmlEditorInsertVar=function(cfg) {
    cfg=cfg||{};
    var box = {w:cfg.width||300, h:cfg.height||300};
    cfg.width = null;delete cfg.width;
    cfg.height = null;delete cfg.height;
	var option = cfg.option; delete cfg.option;
    Ext.apply(this,cfg);
    this.init=function(htmlEditor) {
        this.editor=htmlEditor;
        this.editor.on(
        	'render',
        	function onRender(){
				if( ! Ext.isSafari){
					this.editor.tb.add({
						itemId : 'htmlEditorInsertVar',
						//cls : 'x-btn-icon x-edit-insertimage',
						cls : 'x-btn-icon',
						text:'',
						icon:Pub.ico('var'),
						enableToggle : false,
						scope : this,
						//[{text:'text',handler:function(text){htmlEditor.insertAtCursor(text);}}],
						clickEvent : 'mousedown',
						handler:function(){
							var ds = new Ext.data.ArrayStore({
								fields:['varName','varDesc']
							});
							ds.loadData( typeof(option)=='function' ? eval(option)() : option);						
							new Ext.Window({
								title:"插入变量",
								id:'htmlEditorInsertVar-opthin-win',
								width:box.w,
								height:box.h,
								layout:'fit',
								modal:true,
								items:Pub.grid({
									layout:'fit',autoScroll:true,columnLines :true,
									ds:ds,viewConfig:{forceFit:true},border:false,
									cm:new Ext.grid.ColumnModel([
										new Ext.grid.RowNumberer(),
										{header:"变量",dataIndex:'varName',renderer:function(v){return '{%'+v+'%}';}},
										{header:"说明",dataIndex:'varDesc'}
									]),
									listeners:{
										"rowclick":function(g,row){
					                    	var recordData = g.getStore().getAt(row).data;
					                    	htmlEditor.insertAtCursor('{%'+recordData.varName+'%}');
					                    	Ext.getCmp('htmlEditorInsertVar-opthin-win').close();
										 }
									}
								}),
								constrain:true
							}).show();
						},
						/*tooltip : cfg.buttonTip || {
							title : '插入变量',
							text : '插入变量到编辑器',
							cls : 'x-html-editor-tip'
						},*/
						tabIndex :- 1
					});
				}
			},this
		);
    };
};

Pub.Component.TreeCombobox = Ext.extend(Ext.form.ComboBox, {
		id : '',//选填
		url : '',//必填
		fieldLabel : '下拉树',//选填
		name : '',
		treeRootText : '所有',
		rootVisible : true,	//是否显示根节点
		allowUnLeafClick : false,//false表示不允许非子叶点击选中.
		/******以上为必填或者选填项*******/
		store : new Ext.data.SimpleStore({
			fields : [],
			data : [[]]
		}),
		editable : false,
		autoScroll : false,
		mode : 'local',
		triggerAction : 'all',
		emptyText : '请选择...',
		//width : 150,
		tpl : "<div id='tree'></div>",
		selectedClass : '',
		onSelect : function(){alert(111);},//Ext.emptyFn,
		initComponent : function () {
			Pub.Component.TreeCombobox.superclass.initComponent.call(this);
			/**    * the root of opTree;    */
			this.opRoot = new Ext.tree.AsyncTreeNode({
				id : '0',
				text : this.treeRootText
			});
			/**    * 与后台通讯的加载器     */
			this.loader = new Ext.tree.TreeLoader({
					url : this.url,
					listeners : {
						"beforeload" : function (treeloader, node) {
							treeloader.baseParams = {
								id : node.id
							};
						}
					}
				});
			/** * the opTree used to choose the dep;    */
			this.tree = new Ext.tree.TreePanel({
					anchor : '95%',
					frame : false,
					width : this.width - 5,
					height : 150,
					animate : false,
					rootVisible : this.rootVisible,
					autoScroll : true,
					loader : this.loader,
					root : this.opRoot
				});
			this.comboHidden = new Ext.form.Hidden({
					id : 'comboHidden',
					name : 'hidden',
					value : ''
				});
		},
		/**        
		* ----------------------------------         
		* 树的单击事件处理        
		* @param node,event        
		* ----------------------------------        
		*/
		treeClk : function (node, e) {
			if (!node.isLeaf() && !this.allowUnLeafClick) {
				this.reset();
				e.stopEvent();// 非叶子节点则不触发
				return;
			}
			if (node.id == '0') {
				return;
			}
			this.setValue(node.text);// 设置option值
			this.comboHidden.setValue(node.id);//设置隐藏域值
			this.collapse();// 隐藏option列表
		},
		reset : function () {
			this.setValue();// 重置
			this.comboHidden.setValue();//重置隐藏域值
		},
		//自定义方法去的隐藏域值
		getHidden : function () {
			return this.comboHidden.getValue();
		},
		listeners : {
			'collapse':function(){
				//this.expand();
			},
			'expand' : {
				fn : function () {
					if (!this.tree.rendered && this.tpl) {
						this.tree.render("tree");
					}
					this.tree.show();
				},
				single : true
			},
			'render' : {
				fn : function () {
					this.tree.on('click', this.treeClk, this);
				}
			}
		}
	});
//Ext.reg('pub.component.treecombox', Pub.Component.TreeCombobox);

/*editor:new Ext.form.TwinTriggerField({
								fieldLabel:"图片",anchor:"100%",
								trigger2Class:'extend-x-form-color-trigger',
								trigger1Class:'extend-x-form-up-trigger',
								onTrigger1Click : function(){
									var position = this.getPosition();
									Run.winUpload({										
										x:position[0],
										animateTarget:this.id,
										y:position[1]+23,
										url:Pub.url('Bic/_addProductUploadImg'),
										modal:true,
										title:'添加新图片'
									});
								},
								onTrigger2Click : function(){
									var field = this;
									var position = this.getPosition();
									new Ext.menu.ColorMenu({
										listeners:{
											hide:function(e){e.destroy();},
											select:function(palette,color){
												alert(field.id);
												var row = handle.activeCell.row
												var record = handle.ds.getAt(row);
												record.data['ProdModelOptionValue'] = 'color:#'+color;
												record.commit()
											}
										}
									}).showAt([position[0],(position[1]+23)]);
								}								
							})*/

var Pub4={	
	win:function(cfg){
		var me = this;
		cfg.id = cfg.id|| ('DIY_'+Math.random());
		cfg.animateTarget = cfg.animateTarget || (cfg.aEl || 'xxx-default-aEl');
		var win = Ext.getCmp(cfg.id);		
		if(win || false) win.show();
		else{
			var listeners={beforeclose:function(cmp){
				if(cmp.__diyAllowClose || false){
					return true;
				}else{
					cmp.__diyAllowClose = true;
					setTimeout(function(){me.animClose(cmp.id);},10);
					return false;
				}
			}};
			cfg.listeners = Ext.apply(listeners,cfg.listeners||{});
			Ext4.create('Ext.window.Window',cfg||{}).show();
		}		
		return win;
	},
	animClose:function(id){
		id = id+'';
		var random = (Math.random()+'_');
		//rm = random.substr(5,1);
		rm2= random.substr(4,1);
		//var anchor=['tl','t','tr','l','c','r','bl','b','br','r']
		var anchor=['r','r','r','l','l','l','t','t','b','b'];
		Ext4.fly(id).ghost(anchor[rm2],{callback:function(){
			Ext4.getCmp(id).close();
		}});
	}
};